﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using Telerik.Web.UI;

public partial class Alerts : BasePage
{
	protected override void pageLoad()
	{

		if (!IsPostBack)
		{
			if (Request.Cookies["AlertsPageSize"] != null)
			{
				DropDownList1.SelectedValue = Request.Cookies["AlertsPageSize"].Value;
			}

			ChangePageSize(int.Parse(DropDownList1.SelectedValue));
				

			bindSections();
			bindPeriods();
			bindTeachers();
			Fill();
		}
		else
		{
			if (Request.Cookies["AlertsPageSize"] == null)
			{
				Response.Cookies.Set(new HttpCookie("AlertsPageSize", DropDownList1.SelectedValue));
			}
			else
			{
				Response.Cookies.Set(Request.Cookies["AlertsPageSize"]);
			
			}
			
			Response.Cookies["AlertsPageSize"].Value = DropDownList1.SelectedValue;

		}


		if (Request.Params["__EVENTTARGET"] == "ctl00$ContentPlaceHolder1$gvReport")
		{
			string _params = Request.Params["__EVENTARGUMENT"];

			if (!string.IsNullOrEmpty(_params))
			{

				//GridSortCommandEventArgs e = new GridSortCommandEventArgs(_params.Replace("Sort$", string.Empty), SortDirection.Ascending);
				//rgAlerts_SortCommand(this, e);
			}
		}

		
	}

	protected void bindSections()
	{
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetSectionsShort(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, CurrentInfo.SemesterId, out message).Tables[0];
		CheckSections(data);
		this.Session["Sections"] = data;
		PALogManager.MessageLog(message);

		DataTable dt = data;
		DataRow dr = dt.NewRow();
		dr["SECTION_ID"] = 0;
		dr["SECTION_TITLE"] = " All Sections";
		dt.Rows.InsertAt(dr, 0);
		

		data.DefaultView.Sort = "SECTION_TITLE";
		this.ddlSections.DataSource = data;
		this.ddlSections.DataBind();
	}


	protected void bindPeriods()
	{
		DateTime current;

		if(Teacher.IS_ADMIN == 0)
			this.ddlPeriods.DataSource = Manager.GetWeeks(DateTime.Now, CurrentInfo.FIRSTDAY, CurrentInfo.LASTDAY, out current);
		else
			this.ddlPeriods.DataSource = Manager.GetWeeksForAdmin(DateTime.Now, CurrentInfo.FIRSTDAY, CurrentInfo.LASTDAY, out current);
		if(current != DateTime.MinValue)
			this.ddlPeriods.SelectedValue = current.ToString();

		this.ddlPeriods.DataBind();
	}

	protected void bindTeachers()
	{
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetTeachers(PAConfiguration.ConnectionString, CurrentInfo.SemesterId, out message).Tables[0];
		PALogManager.MessageLog(message);
		data.DefaultView.Sort = "TEACHER_NAME";
		this.ddlTeachers.DataSource = data;
			
		this.ddlTeachers.DataBind();

//		ddlTeachers.Enabled = (Teacher.IS_ADMIN == 1);

		if (Teacher.IS_ADMIN == 0)
		{
			ddlTeachers.SelectedValue = Teacher.TEACHER_ID.ToString();
		}
	}

	public override string getHeader(DataControlFieldCollection dt)
	{
		StringBuilder sb = new StringBuilder();

		sb.Append("<table  name='headertable' class='stats' cellspacing='0' rules='all'  border='1' id='headertable' style='width:100%;border-collapse:collapse;' >");
		sb.Append("<tr class='hed2'>");
		string sortimage = string.Empty;
		
		foreach (DataControlField dc in dt)
		{
			if (dc.SortExpression == SortExpression)
			{
				if (isAsc)
				{
					sortimage = "<img src='images/darrow.gif' style='border-width:0px;' />";
				}
				else
				{
					sortimage = "<img src='images/uarrow.gif' style='border-width:0px;' />";
				}
			}
			else
			{
				sortimage = string.Empty;
			}

			sb.AppendFormat(
"<th scope='col'><a href=\"javascript:__doPostBack('ctl00$ContentPlaceHolder1$gvReport','Sort${1}')\">{0}</a>{2}</th>", dc.HeaderText, dc.SortExpression, sortimage);
		}

		sb.Append("</tr>");
		sb.Append("</table>");

		return sb.ToString();
	}

	protected override void Fill()
	{
		string message = string.Empty;
		DataLayer dal = new DataLayer();

		if (ddlSections.SelectedValue == string.Empty)
			return;

		
		if (ddlPeriods.SelectedValue == string.Empty)
			return;

		DataSet results = dal.GetAlerts(PAConfiguration.ConnectionString,
			decimal.Parse(ddlSections.SelectedValue),
			DateTime.Parse(ddlPeriods.SelectedValue),
			decimal.Parse(ddlTeachers.SelectedValue),
			out message);

		PALogManager.MessageLog(message);

		DataTable dt = null;

		if ((results == null) || (results.Tables.Count == 0))
		{
			rgAlerts.DataSource = null;
			rgAlerts.DataBind();
			return;
		}
		dt = results.Tables[0];

		if (!string.IsNullOrEmpty(Sorting))
		{
			dt.DefaultView.Sort = Sorting;
		}



		rgAlerts.DataSource = dt;
		rgAlerts.DataBind();
	}



	public override string Icon
	{
		get
		{
			return "images/attendance_alerts_icon.png";
		}
	}

	protected void ChangePageSize(int pagesize)
	{
		
		if (pagesize > 0)
		{
			rgAlerts.PageSize = pagesize;
			rgAlerts.AllowPaging = true;
		}
		else
			rgAlerts.AllowPaging = false;

	}

	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
	{
		ChangePageSize(int.Parse(DropDownList1.SelectedValue));
		
		Fill();
	}

	protected void lbExport_Click(object sender, ImageClickEventArgs e)
	{
		string message = string.Empty;
		DataLayer dal = new DataLayer();

		if (ddlSections.SelectedValue == string.Empty)
			return;


		if (ddlPeriods.SelectedValue == string.Empty)
			return;

		DataSet toExcel = dal.GetAlerts(PAConfiguration.ConnectionString,
			decimal.Parse(ddlSections.SelectedValue),
			DateTime.Parse(ddlPeriods.SelectedValue),
			decimal.Parse(ddlTeachers.SelectedValue),
			out message);


		PALogManager.MessageLog(message);
		Manager.ExportToCSV(
			toExcel.Tables[0],
			this.Context,
			"Alerts.csv");
	}
	protected void bGo_Click(object sender, ImageClickEventArgs e)
	{
		lbExport.Visible = true;
		Sorting = "SECTION_NAME ASC";
		Fill();
	}


	protected void rgAlerts_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
	{
		Sort(e);
	}

	protected void rgAlerts_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
	{
		Fill();
	}

	protected void rgAlerts_ItemDataBound(object sender, GridItemEventArgs e)
	{
		if( (e.Item.ItemType != GridItemType.AlternatingItem) &&
(e.Item.ItemType != GridItemType.Item))

			return;

		DataRow row = ((DataRowView)e.Item.DataItem).Row;

		if (Teacher.IS_ADMIN == 0)
		{
			if (Session["Sections"] != null)
			{
				DataTable sections = (DataTable)Session["Sections"];
				bool isfind = false;

				foreach (DataRow dr in sections.Rows)
				{
					if ((decimal)dr["SECTION_ID"] == (decimal)row["SECTION_ID"])
					{
						isfind = true;
						break;
					}
				}

				if (isfind)
				{
					HyperLink link = (HyperLink)e.Item.FindControl("HyperLink1");
					link.NavigateUrl = string.Format("entry.aspx?sectionId={0}&date={1:d}", row["SECTION_ID"], DateTime.Parse(ddlPeriods.SelectedValue));
				}
			}
		}
		else
		{

			HyperLink link = (HyperLink)e.Item.FindControl("HyperLink1");
			link.NavigateUrl = string.Format("entry.aspx?sectionId={0}&date={1:d}", row["SECTION_ID"], DateTime.Parse(ddlPeriods.SelectedValue));
		}
	}
}
